<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AJAX封装</title>
</head>
<body>
  <button id="btn">点击获取数据</button>
  <script>
    // 定义请求 url
    let req_url = 'https://api.apiopen.top/getJoke';

    function sendAJAX(url) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.send();
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status <300) {
              resolve(xhr.response); // 成功则返回响应数据
            } else {
              reject(xhr.status); // 失败则返回响应状态码
            }
          }
        }
      })
    }

    // 获取按钮元素
    const btn = document.getElementById('btn');
    // 给按钮元素绑定点击事件
    btn.onclick = async function() {
      let result = await sendAJAX(req_url);
      console.log(result);
    }    
  </script>
</body>
</html>